package com.atguigu.chapter11;

import com.atguigu.chapter05.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.annotation.DataTypeHint;
import org.apache.flink.table.annotation.FunctionHint;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.AggregateFunction;
import org.apache.flink.table.functions.TableFunction;
import org.apache.flink.types.Row;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.call;

/**
 * TODO
 *
 * @author cjp
 * @version 1.0
 * @date 2021/3/12 9:30
 */
public class Flink23_UDAF {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<WaterSensor> sensorDS = env
                .socketTextStream("localhost", 9999)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        // 切分
                        String[] line = value.split(",");
                        return new WaterSensor(line[0], Long.parseLong(line[1]), Integer.parseInt(line[2]));

                    }
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((value, ts) -> value.getTs() * 1000L)
                );


        // TODO - UDTF
        // 1.创建 表的执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);
        // 2.将 流 转换成 Table
        tableEnv.createTemporaryView("sensor", sensorDS, $("id"), $("ts"), $("vc"), $("et").rowtime());
        Table sensor = tableEnv.from("sensor");


        tableEnv.createTemporarySystemFunction("vcavg",VcAvg.class);

        // TableAPI的方式
//        sensor
//                .groupBy($("id"))
//                .select($("id"),call("vcavg",$("vc")).as("vcAvg"))
//                .execute()
//                .print();


        // SQL的方式
        tableEnv
                .sqlQuery("select id,vcavg(vc) as vcAvg from sensor group by id")
                .execute()
                .print();

        env.execute();
    }

    public static class VcAvg extends AggregateFunction<Double, SumAndCount> {


        @Override
        public Double getValue(SumAndCount accumulator) {
            return accumulator.getVcSum() * 1D / accumulator.getVcCount();
        }

        @Override
        public SumAndCount createAccumulator() {
            return new SumAndCount();
        }

        public void accumulate(SumAndCount acc, Integer vc) {
            acc.setVcSum(acc.getVcSum() + vc);
            acc.setVcCount(acc.getVcCount() + 1);
        }
    }
}

/**
 */
